﻿using System.Collections.Generic;
using System.Text;

namespace ProblemsSet
{
    public class Problem_26 : BaseProblem
    {
        public override object GetResult()
        {
            const long max = 1000;
            long res = 0;
            long val = 1;
            long tmp = 0;
            for (var i = 2; i < max; i++)
            {
                DivideString(1, i, out tmp);
                if (tmp > res)
                {
                    val = i;
                    res = tmp;
                }
            }
            return val;
        }

        public static string DivideString(long value1, long value2, out long cycle)
        {
            cycle = 0;
            if (value1 == 0) return "0";
            var rs = new StringBuilder();
            var dividers = new List<long>();
            var pointExists = false;
            while (value1 > 0)
            {
                bool isFirst = true;
                while (value1/value2 <= 0)
                {
                    value1 *= 10;
                    if (!pointExists)
                    {
                        if (rs.Length == 0) rs.Append("0.");
                        else rs.Append(".");
                        pointExists = true;
                    }
                    if (isFirst)
                    {
                        isFirst = false;
                        continue;
                    }
                    rs.Append("0");

                }
                if (dividers.Contains(value1))
                {
                    cycle = dividers.Count - dividers.IndexOf(value1);
                    return rs.ToString();
                }
                dividers.Add(value1);
                rs.Append(value1/value2);
                value1 = value1%value2;
            }
            return rs.ToString();
        }

        public override string Problem
        {
            get
            {
                return @"A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

1/2	= 	0.5
1/3	= 	0.(3)
1/4	= 	0.25
1/5	= 	0.2
1/6	= 	0.1(6)
1/7	= 	0.(142857)
1/8	= 	0.125
1/9	= 	0.(1)
1/10	= 	0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d  1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.";
            }
        }

        public override bool IsSolved
        {
            get
            {
                return true;
            }
        }

        public override object Answer
        {
            get
            {
                return 983;
            }
        }

    }
}
